package com.jnc.web.biz.system.service.impl;

import com.jnc.common.constant.SysConstant;
import com.jnc.common.util.convert.ConvertUtil;
import com.jnc.core.base.model.User;
import com.jnc.core.base.service.UserService;
import com.jnc.web.biz.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: jjn
 * @Date: 2018/9/19
 * @Desc:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> queryUser(User record) {
        return userMapper.queryUser(record);
    }

    @Override
    public User getUser(Integer userId) {
        return userMapper.getUser(userId);
    }

    @Override
    public List<User> checkUser(User record) {
        return userMapper.checkUser(record);
    }

    @Transactional(value = SysConstant.TX_BASE_NAME)
    @Override
    public int deleteUser(String ids) {
        List<Integer> list = ConvertUtil.toIntList(ids);
        int count = userMapper.deleteUser(list);
        if(count > 0){
            userMapper.deleteUserRoles(list);
        }
        return count;
    }

    @Transactional(value = SysConstant.TX_BASE_NAME)
    @Override
    public int addUser(User record) {
        int userId = userMapper.addUser(record);
        if(userId > 0){
            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            map.put("list", record.getRoles());
            userMapper.addUserRole(map);
        }
        return userId;
    }

    @Transactional(value = SysConstant.TX_BASE_NAME)
    @Override
    public int editUser(User record) {
        int count = userMapper.editUser(record);
        if(count > 0){
            userMapper.deleteUserRole(record.getUserId());
            Map<String, Object> map = new HashMap<>();
            map.put("userId", record.getUserId());
            map.put("list", record.getRoles());
            userMapper.addUserRole(map);
        }
        return count;
    }

    @Override
    public int editPW(User record) {
        return userMapper.editPW(record);
    }

    @Override
    public User getUserByLoginName(String loginName) {
        return userMapper.getUserByLoginName(loginName);
    }

}
